/*
 * Alberto Ruiz-Larrea Guillén...11383
 * Erdi Dogruel..................14955
 * Marcos Pérez Martín...........10324
 */

package com.example.database;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;

//This class insert the leaderboard table
public class InsertLeaderBoard extends AsyncTask<OpenDB, Integer, String> {

	@Override
	protected String doInBackground(OpenDB... params) {

		// works fine
		SQLiteDatabase read = params[0].getReadableDatabase();
		String[] columns = new String[] { OpenDB.id, OpenDB.name,
				OpenDB.rating, OpenDB.selected };
		String[] col_player = { OpenDB.id, OpenDB.name, OpenDB.position,
				OpenDB.team, OpenDB.rating };
		Cursor cursor = read.query(OpenDB.table1, columns, null, null, null,
				null, null);
		cursor.moveToFirst();

		SQLiteDatabase write = params[0].getWritableDatabase();
		ContentValues values = new ContentValues();

		while (!cursor.isAfterLast()) {

			Cursor c = read.query(OpenDB.table2, col_player,
					OpenDB.team + "=?", new String[] { cursor.getString(1) },
					null, null, null, null);

			c.moveToFirst();
			int i = 0;
			int sum = 0;

			while (!c.isAfterLast()) {
				sum = sum + c.getInt(4);
				i++;
				c.moveToNext();
			}
			if (sum != 0 && i != 0)
				sum = sum / i;

			values.put(OpenDB.name, cursor.getString(1));
			values.put(OpenDB.games_played, 0);
			values.put(OpenDB.won_matches, 0);
			values.put(OpenDB.draw_matches, 0);
			values.put(OpenDB.lost_matches, 0);
			values.put(OpenDB.score_home, 0);
			values.put(OpenDB.score_away, 0);
			values.put(OpenDB.points, 0);
			values.put(OpenDB.rating, sum);
			write.insert(OpenDB.table4, null, values);
			cursor.moveToNext();
		}
		cursor.close();
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		if (result == "-1") {
			Log.e("Insert", "Error while insert leaderboard in DB");
		}
	}
}
